package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DemoUser;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/demo")
public class DemoController {
    @RequestMapping("/response")
    //测试一下返回响应数据
    public void testResponse(HttpServletResponse response)  {
        //浏览器返回的类型是HTML
//        response.setContentType("text/html;charset=utf-8");
        try(
                PrintWriter writer = response.getWriter();
                ){
            writer.write("<h1>hello,this is a response demo!</h1>");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/request")
    public void testRequest(HttpServletRequest request,HttpServletResponse response){
        System.out.println(request.getMethod());//请求方法
        System.out.println(request.getServletPath());//请求路径
        Enumeration<String> enumeration = request.getHeaderNames();

        while(enumeration.hasMoreElements()){
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name+":"+value);
        }

        response.setContentType("text/html;charset=utf-8");
        try(
                PrintWriter writer = response.getWriter();
        ){
            writer.write("<h1>i get your request</h1>");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

//    /students?current=1&limit=20
    @RequestMapping(path = "/students" , method = RequestMethod.GET)
    @ResponseBody//返回一个简单的字符串
    //要怎么获取请求的参数呢？方法的参数名称与请求的参数名称一致就行了
    //DispatcherServlet检测到方法有参数之后，就会把请求中与之匹配的参数传进来
    //如果请求没有传来参数怎么办呢？需要在方法参数前面加上注解。注解中第二个参数：可以不传；第三个参数：不传的话默认值
    public String getStudents(
            @RequestParam(name = "current",required = false,defaultValue = "1") int current ,
            @RequestParam(name = "limit",required = false,defaultValue = "10") int limit){
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    //2 根据学生id查询一个学生的信息：/student/123 直接把参数编排到路径中
    @RequestMapping(path = "/student/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id){
        System.out.println(id);
        return "a student";
    }
    @RequestMapping(path = "/student",method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name1,int age){
        System.out.println("姓名："+name1+"，年龄："+age);
        return "success!";
    }

    //返回html文件
    @RequestMapping(path = "/teacher" ,method = RequestMethod.GET)
    public ModelAndView getTeacher(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "李老师");
        mav.addObject("age", 30);
        mav.setViewName("/test/view2");
        return mav;
    }

    @RequestMapping(path = "/school",method = RequestMethod.GET)
    public String getSchool(Model model){
        model.addAttribute("name","电子科技大学");
        model.addAttribute("age",65);
        return "/test/view2";
    }

    @RequestMapping(path = "/emp",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp(){
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000);
        return emp;
    }

    @RequestMapping(path = "/emps",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps(){
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "李四");
        emp.put("age", 24);
        emp.put("salary", 9000);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "王五");
        emp.put("age", 22);
        emp.put("salary", 8000);
        list.add(emp);

        return list;
    }

    @RequestMapping("/index")
    public String seeIndex(){
        return "/index";
    }

    //测试将数据封装成DemoUser传入Controller
    @RequestMapping(path = "/regist",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> test(DemoUser user){
        Map<String, Object> map = new HashMap<>();
        if(user==null){
            map.put("error","未收到DemoUser类");
        }else{
            map.put("success","收到DemoUser类");
            System.out.println(user);
        }
        return map;
    }

    //ajax示例
    @RequestMapping(path = "/ajax",method = RequestMethod.POST)
    @ResponseBody
    public String testAjax(String name,int age){
        System.out.println("name:"+name+";age:"+age);//代表处理数据的过程
        //异步返回
        return CommunityUtil.getJSONString(0, "操作成功！");
    }

    //异步注册
    @RequestMapping(path = "/registAjax",method = RequestMethod.POST)
    @ResponseBody
    public String testRegist(String username){
        System.out.println(username);
        if(username.equals("小明")){
            return CommunityUtil.getJSONString(0,"该名字已被占用");
        }else{
            return CommunityUtil.getJSONString(1, "该名称尚未被使用");
        }

    }

    //测试服务器给浏览器发送cookie
    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response){
        Cookie cookie = new Cookie("code",CommunityUtil.generateUUID());
        cookie.setPath("/community");
        cookie.setMaxAge(60*10);//不设置生存时间的话，默认关闭浏览器cookie就消失，设置的话浏览器会存到本地
        response.addCookie(cookie);
        return "set cookie success";
    }
    //对比不设置cookie的
    @RequestMapping(path = "/nocookie",method = RequestMethod.GET)
    @ResponseBody
    public String noCookie(){
        return "no cookie";
    }

    //
    @RequestMapping(path = "/cookie/get",method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code){
        System.out.println(code);
        return "get cookie";
    }

    //session示例
    @RequestMapping(path = "session/set",method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session){
        session.setAttribute("id", 1);
        session.setAttribute("name","test");
        return "set session";

    }
    @RequestMapping(path = "session/get",method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session){
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

}
